<template>
  <div class="exercise-container">
    <h2 class="page-title">
      删除练习
    </h2>

    <!-- 班级选择框（教师可见，使用 classes 替代 teacherClasses） -->
    <div
      v-if="classes?.length > 0"
      class="mb-4 text-left"
    >
      <label class="form-label">选择班级</label>
      <select
        v-model="selectedClassId"
        class="form-control"
        :disabled="!classes?.length"
        @change="handleClassChange"
      >
        <option value="">
          请选择班级
        </option>
        <option
          v-for="cls in classes"
          :key="cls.classesId"
          :value="cls.classesId"
        >
          {{ cls.classesName }}
        </option>
      </select>
      <div
        v-if="!selectedClassId"
        class="text-danger mt-1"
      >
        请选择要管理的班级
      </div>
    </div>

    <!-- 加载状态 -->
    <div
      v-if="loading"
      class="loading"
    >
      加载中...
    </div>

    <!-- 错误提示 -->
    <div
      v-if="error"
      class="error"
    >
      {{ error }}
    </div>

    <div v-else>
      <!-- 练习列表 -->
      <div 
        v-if="exercises.length > 0" 
        class="exercise-grid grid gap-4"
      >
        <div 
          v-for="item in exercises" 
          :key="item.exercise.exerciseId" 
          class="exercise-card cursor-pointer transition-all"
        >
          <div class="card-body p-4">
            <div class="flex justify-between items-start mb-3">
              <h5 class="card-title">
                {{ item.exercise.exerciseName }}
              </h5>
            </div>
            <p class="card-text">
              总分：{{ item.exercise.exerciseScore || 0 }}分<br>
              开始时间：{{ formatTime(item.exercise.exerciseStartTime) }}
            </p>
            <div class="mt-4 text-right">
              <button 
                class="btn btn-danger" 
                @click="confirmDelete(item.exercise.exerciseId)"
              >
                删除
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 无数据提示 -->
      <div 
        v-else 
        class="no-data提示 text-center"
      >
        <i class="fa fa-inbox text-4xl mb-4" />
        <p class="text-lg">
          暂无可删除的练习
        </p>
        <p class="text-sm mt-2">
          请先添加练习后再进行操作
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  props: {
    userId: { type: String, required: true },
    courseId: { type: String, required: true },
    // 关键修改：将 teacherClasses 改为 classes，并设置默认空数组
    classes: { type: Array, default: () => [] }
  },
  data() {
    return {
      loading: true,
      error: null,
      exercises: [],
      selectedClassId: ''
    };
  },
  mounted() {
    // 关键修改：检查 classes 长度（替代 teacherClasses）
    if (this.classes?.length > 0) {
      this.selectedClassId = this.classes[0].classesId;
      this.fetchExercises();
    } else {
      this.loading = false; // 无班级时停止加载
    }
  },
  methods: {
    async handleClassChange() {
      if (!this.selectedClassId) {
        this.exercises = [];
        return;
      }
      this.fetchExercises();
    },

    async fetchExercises() {
      this.loading = true;
      this.error = null;

      try {
        if (!this.selectedClassId) {
          this.exercises = [];
          return;
        }

        const response = await axios.get(`/api/exercises/class/${this.selectedClassId}`);

        if (Array.isArray(response.data)) {
          this.exercises = response.data.map(exercise => ({ exercise }));
        } else {
          this.exercises = [];
        }
      } catch (err) {
        console.error('获取练习失败:', err);
        this.error = '获取练习列表失败，请重试';
      } finally {
        this.loading = false;
      }
    },

    confirmDelete(exerciseId) {
      const confirmed = window.confirm('确定要删除该练习吗？此操作将永久删除练习及关联数据。');
      if (confirmed) {
        this.deleteExercise(exerciseId);
      }
    },

    async deleteExercise(exerciseId) {
      try {
        await axios.post(`/api/exercises/cascade/${exerciseId}`);
        this.fetchExercises(); 
        alert('删除成功');
      } catch (err) {
        console.error('删除练习失败:', err);
        alert('删除失败，请重试');
      }
    },

    formatTime(timeStr) {
      const date = new Date(timeStr);
      return `${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')} ${String(date.getHours()).padStart(2,'0')}:${String(date.getMinutes()).padStart(2,'0')}`;
    }
  }
};
</script>

<style scoped>
/* 导入公共样式 */
@import '../../assets/css/exercise_css/ExerciseCommon.css';

/* 班级选择框样式 */
.form-label {
  font-weight: 600;
  margin-bottom: 0.5rem;
  color: #2c3e50;
}

.form-control {
  padding: 0.375rem 0.75rem;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  width: 300px;
}

/* 删除按钮样式 */
.btn-danger {
  background-color: #ef4444;
  border-color: #ef4444;
  color: white;
}

.btn-danger:hover {
  background-color: #dc2626;
  border-color: #dc2626;
}
</style>
